import ujson

from flask import request
from flask_restful import Resource
from sqlalchemy.exc import DatabaseError

from app.models import Dept, Emp
from app.utils import get_redis_conn


class DeptListAPI(Resource):

    @staticmethod
    def get():
        data = get_redis_conn().get('hrs:api:depts')
        if data:
            depts = ujson.loads(data)
        else:
            depts = [dept.to_dict() for dept in Dept.query.all()]
            get_redis_conn().set('hrs:api:depts', ujson.dumps(depts), ex=1800)
        return {'depts': depts}

    @staticmethod
    def post():
        try:
            Dept(**request.json).save_or_update()
            get_redis_conn().delete('hrs:api:depts')
            return {'code': 10000, 'message': '新增部门成功'}
        except DatabaseError:
            return {'code': 10002, 'message': '新增部门失败'}


class DeptAPI(Resource):

    @staticmethod
    def delete(no):
        try:
            Dept.query.filter_by(no=no).one().delete()
            get_redis_conn().delete('hrs:api:depts')
            return {'code': 10000, 'message': '删除部门成功'}
        except DatabaseError:
            return {'code': 10002, 'message': '删除部门失败'}


class EmpListAPI(Resource):

    @staticmethod
    def get():
        dno = request.args.get('dno')
        if dno:
            data = get_redis_conn().get(f'hrs:api:emps:{dno}')
            if data:
                emps = ujson.loads(data)
            else:
                emps = Emp.query.filter_by(dno=dno).all()
                emps = [emp.to_simple_dict() for emp in emps]
                get_redis_conn().set(f'hrs:api:emps:{dno}', ujson.dumps(emps), ex=900)
        else:
            emps = [emp.to_full_dict() for emp in Emp.query.all()]
        return {'emps': emps}
